package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author junjie.yang
 * @date 2023/12/26
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private StateMachine<OrderStatusEnum, OrderStatusChangeEventEnum> orderStateMachine;

    private long id =1L;

    private Map<Long, Order> orders = new ConcurrentHashMap<>();

    @Override
    public Order create() {
        Order order =new Order();
        order.setOrderStatus(OrderStatusEnum.WAIT_PAYMENT);
        order.setOrderId(id++);
        orders.put(order.getOrderId(), order);
        System.out.println("订单创建成功:"+ order);
        return order;
    }

    @Override
    public Order pay(long id) {
        Order order = orders.get(id);
        System.out.println("尝试支付，订单号："+ id);
        Message<OrderStatusChangeEventEnum> message = MessageBuilder.withPayload(OrderStatusChangeEventEnum.PAYED).
                setHeader("order", order).build();
        orderStateMachine.sendEvent(Mono.just(message));
        return order;
    }

    @Override
    public Order deliver(long id) {
        Order order = orders.get(id);
        System.out.println(" 尝试发货，订单号："+ id);
        Message<OrderStatusChangeEventEnum> message = MessageBuilder.withPayload(OrderStatusChangeEventEnum.DELIVERY)
                .setHeader("order", order).build();
        orderStateMachine.sendEvent(Mono.just(message));
        return order;
    }

    @Override
    public Order receive(long id) {
        Order order = orders.get(id);
        System.out.println(" 尝试收货，订单号："+ id);
        Message<OrderStatusChangeEventEnum> message = MessageBuilder.withPayload(OrderStatusChangeEventEnum.RECEIVED)
                .setHeader("order", order).build();
        orderStateMachine.sendEvent(Mono.just(message));
        return order;
    }

    @Override
    public Map<Long, Order> getOrders() {
        return orders;
    }
}
